import React,{useEffect,useState} from 'react'
import Pagecomponent from './pageComponent/Pagecomponent';
import './Eat.css'

var pageNum;
const Eat = () => {
    const [dataList, setDataList] = useState([]);
    const [totalPage, setTotalPage] = useState(15);
    const [fname, setFname] = useState('');
    const [fmater, setFmater] = useState('');
    const [fstep, setFstep] = useState('');
    const [pic, setPic] = useState('');

    const [eat,setEat] = useState([]);

    useEffect(()=>{
        fetch(`https://api.124ss.xyz:2355/endeat?rand=$1`,{
          method: "GET",
          mode: "cors",
          headers: {
            "Content-Type": "text/plain"
          }
    
        }).then(res => {
          return res.json();
        })
        .then(res =>{
            var arr = [];
            var eatObj = [];
            res.forEach((item,index) => {
                eatObj = [
                    item['food_id'],
                    item['food_image'],
                    item['food_name'],
                    item['food_material'],
                    item['food_step']
                ]
                arr.push(eatObj)
            } )
            setEat(arr)
        })
        .catch((err)=>{
          console.log("err:",err);
        })
      },[]
    )

    const DelItem = (idx,item) => {
  
        fetch(`https://api.124ss.xyz:2355/enddelEat/${item[0]}`,{
          method: "delete",
          mode: "cors",
          headers: {
            "Content-Type": "text/plain"
          },
          body: JSON.stringify({
            food_id: item[0]
          })
    
        }).then(res => {
          return res.text();
        })
        .then(res =>{
          console.log(res)
        } )
        .catch((err)=>{
          console.log("err:",err);
        })
    
        let newEat = eat.filter((_,index)=>idx!=index);
        setEat(newEat);
    }

    const AddFood = () => {
      // let file = pic[0]
      // let fm = new FormData()
      // fm.append('image', file)

      // fetch(`https://api.124ss.xyz:2355/admin/image`,{
      //   method: "post",
      //   mode: "cors",
      //   headers: {
      //     "Content-Type": "multipart/form-data"
      //   }, 
      //   body: fm
  
      // }).then(res => {
      //   return res.text();
      // })
      // .then(res =>{
      //   alert('添加成功！')
      // } )
      // .catch((err)=>{
      //   alert('添加失败')
      //   console.log("err:",err);
      // })

      // fetch(`https://api.124ss.xyz:2355/images`,{
      //     method: "GET",
      //     mode: "cors",
      //     headers: {
      //       "Content-Type": "text/plain"
      //     }
    
      //   }).then(res => {
      //     return res.json();
      //   })
      //   .then(res =>{
      //       console.log(res)
      //   })
      //   .catch((err)=>{
      //     console.log("err:",err);
      //   })


      fetch(`https://api.124ss.xyz:2355/addFood`,{
          method: "post",
          mode: "cors",
          headers: {
            "Content-Type": "text/plain"
          },
          body: JSON.stringify({
            food_id: 92,
            food_name: fname,
            food_material: fmater,
            food_step: fstep
          })
    
        }).then(res => {
          return res.text();
        })
        .then(res =>{
          // alert('添加成功！')
        } )
        .catch((err)=>{
          // alert('添加失败')
          console.log("err:",err);
        })
    }

    const getCurrentPage = (currentPage) => {
        setDataList(eat[currentPage-1])
        pageNum = currentPage;
      }
    return (
        <div id='eat-container'>
          <div>
            {/* <input type="file" name="file"   onChange={e => {setPic(e.target.files)}}/> */}
            <input style={{width:'200px',height:'30px'}}
                  value = {fname}
                  onChange = {e => {setFname(e.target.value)}} 
                  placeholder = '菜名'
            />
            <input style={{width:'200px',height:'30px'}}
                  value = {fmater}
                  onChange = {e => {setFmater(e.target.value)}} 
                  placeholder = '食材'
            />
            <input style={{width:'200px',height:'30px'}}
                  value = {fstep}
                  onChange = {e => {setFstep(e.target.value)}} 
                  placeholder = '步骤'
            />
            <button onClick={() => AddFood()}>添加</button>
          </div>
          <div id='eat-table'>
            <table id='eat-tab'>
                <thead>
                    <tr>
                        <th>序号</th>
                        <th style={{width: 200}}>菜名</th>
                        <th>食材</th>
                        <th>步骤</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                {
                    eat.slice(3*(pageNum-1),3*pageNum).map((item, index) =>
                    <tr key={index}>
                        {/* <td>
                            <img style={{width: 80, height: 80, borderRadius: 50}} src={'https://api.124ss.xyz:2355/images/' + item[1]} />
                        </td> */}
                        <td>
                          {(pageNum-1)*3+index+1}
                        </td>
                        <td>{item[2]}</td>
                        <td>{item[3]}</td>
                        <td>{item[4]}</td>
                        <td>
                            <button id='eat-btn' onClick={() => DelItem(index,item)}>
                                删除
                            </button>
                        </td>
                    </tr>)
                }
                </tbody>
            </table>
          </div>
          
          <div id='eat-page'>
            <Pagecomponent totalPage={totalPage} pageCallbackFn={getCurrentPage}/>
          </div>
        </div>
    )
}

export default Eat
